package com.haier.npt.redis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @Description:
 * @author: lixu
 * @date:   2018年7月18日 下午2:00:29   
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

    private static final String CACHE_PREFIX = "SpringCache:";

    @Value(value = "${spring.application.name:default}:")
    private String applicationName;

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            String key = CACHE_PREFIX + applicationName;
            key += target.getClass().getName() + "#";
            key += method.getName() + ":";
            for (Object obj : params) {
                key += obj.toString();
            }
            return key;
        };
    }

    @Bean
    @DependsOn("stringRedisTemplate")
    public CacheManager redisCacheManager(StringRedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }
}
